/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.system.service.impl;


import com.koron.common.bean.SecretBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.stub.Port;
import com.koron.system.domain.Message;
import com.koron.system.mapper.MessageMapper;
import com.koron.system.service.api.MessageService;
import com.koron.system.utils.BusinessCode;
import com.koron.workflow.bean.MessageEntity;
import com.koron.workflow.service.api.WorkflowService;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.util.*;

@Service
public class MessageServiceImpl implements MessageService {
    @Value("${app.orgCode}")
    private String orgCode;
    @Value("${app.appid}")
    private String appId;

    @Value("${app.secret}")
    private String secret;
    private final static  Logger logger = LoggerFactory.getLogger(MessageServiceImpl.class);

    @Autowired
    private WorkflowService workflowService;

    @Override
    public MessageBean<Integer> save(Message message) {
        MessageBean<Integer> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            Integer value = 0;
            if (StringUtils.isEmpty(message.getTitle())) {
                msg.setCode(BusinessCode.MESSAGE_EMPTY_TITLE.getCode());
                msg.setDescription(BusinessCode.MESSAGE_EMPTY_TITLE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(message.getContent())) {
                msg.setCode(BusinessCode.MESSAGE_EMPTY_CONTENT.getCode());
                msg.setDescription(BusinessCode.MESSAGE_EMPTY_CONTENT.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(message.getReceiverCode())) {
                msg.setCode(BusinessCode.MESSAGE_EMPTY_RECEIVERCODE.getCode());
                msg.setDescription(BusinessCode.MESSAGE_EMPTY_RECEIVERCODE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(message.getId())) {
                //新增
                message.setId(DefaultIdGenerator.getInstance().generateLongId());
                message.setAddTime(message.getUpdateTime());
                message.setAddUser(message.getUpdateUser());
                message.setIsRead(0);
                message.setIsRemove(0);
                value = factory.getMapper(MessageMapper.class).insert(message);
            } else {
                //修改
                value = factory.getMapper(MessageMapper.class).update(message);
            }
            if (value > 0) {
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("保存消息成功");
                msg.setData(value);
                return msg;
            } else {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("保存消息失败");
                msg.setData(value);
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public Integer batchInsert(List<Message> messageList) {
        try (SessionFactory factory = new SessionFactory()) {
            for (Message message : messageList) {
                message.setId(DefaultIdGenerator.getInstance().generateLongId());
                message.setAddUser(message.getUpdateUser());
                message.setAddTime(message.getUpdateTime());
                message.setIsRead(0);
                message.setIsRemove(0);
            }
            Integer value = factory.getMapper(MessageMapper.class).batchInsert(messageList);
            return value;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    @Override
    public Integer batchUpdate(List<Message> messageList) {
        try (SessionFactory factory = new SessionFactory()) {
            Integer value = factory.getMapper(MessageMapper.class).batchUpdate(messageList);
            return value;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    @Override
    public Integer batchDelete(List<String> idList) {
        try (SessionFactory factory = new SessionFactory()) {
            Integer value = factory.getMapper(MessageMapper.class).batchDeteleLogic(idList);
            return value;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    @Override
    public Message queryOne(String id) {
        try (SessionFactory factory = new SessionFactory()) {
            Message message = factory.getMapper(MessageMapper.class).queryOne(id);
            return message;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    @Override
    public MessageBean<DataBean<Message>> queryByCondition(String receiverCode, Date startTime, Date endTime, Integer start, Integer rows,String keyword) {
        MessageBean<DataBean<Message>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<Message> list = factory.getMapper(MessageMapper.class).queryByCondition(receiverCode, startTime, getnowEndTime(endTime), start, rows,keyword);
            Integer totalNumber = factory.getMapper(MessageMapper.class).countByCondition(receiverCode, startTime, getnowEndTime(endTime),keyword);
            rows = rows == null ? totalNumber : (rows <= 0 ? 1 : rows);
            Integer totalPage = totalNumber > rows ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            DataBean<Message> dataBean = new DataBean<>();
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            list.forEach(item -> fillReceiverName(item));
            dataBean.setList(list);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取消息列表成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }


    @Override
    public MessageBean<Integer> updateIsRead(String id) {
        MessageBean<Integer> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            Message message = queryOne(id);
            if (null == message) {
                msg.setCode(BusinessCode.MESSAGE_NOT_EXISIT.getCode());
                msg.setDescription(BusinessCode.MESSAGE_NOT_EXISIT.getDescription());
                return msg;
            }
            message.setIsRead(1);
            Integer value = factory.getMapper(MessageMapper.class).update(message);
            if (value > 0) {
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("已阅读消息");
                msg.setData(value);
                return msg;
            } else {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("阅读消息失败");
                msg.setData(value);
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    private Message fillReceiverName(Message bean) {
        Port port = getPort();
        if (null != bean) {
            if (StringUtils.isNotEmpty(bean.getReceiverCode())) {
                List<StaffBean> staffBeans = port.staff(bean.getReceiverCode(), null).getData();
                bean.setReceiverName((staffBeans == null && staffBeans.size() > 0) ? staffBeans.get(0).getName() : null);
            }
        }
        return bean;
    }

    public Port getPort() {
        SecretBean secretBean = new SecretBean();
        secretBean.setAppid(appId);
        secretBean.setSecret(secret);
        return new Port(secretBean);
    }

    private Date getnowEndTime(Date date) {
        if (null != date) {
            Calendar todayEnd = Calendar.getInstance();
            todayEnd.setTime(date);
            todayEnd.set(Calendar.HOUR_OF_DAY, 23);
            todayEnd.set(Calendar.MINUTE, 59);
            todayEnd.set(Calendar.SECOND, 59);
            todayEnd.set(Calendar.MILLISECOND, 999);
            return todayEnd.getTime();
        } else {
            return null;
        }
    }


    /**
     * 获取是否有未读消息，待办任务，待审流程
     *
     * @param factory
     * @param user
     * @return
     */
    @Override
    public MessageBean getAllState(SessionFactory factory, StaffBean user) {
        MessageBean msg = new MessageBean();
        try {
            // 获取是否有未读消息
            Integer isReadCount = factory.getMapper(MessageMapper.class).getIsReadCount(user.getCode(), 0);
            // 获取是否有待办任务
            Integer toDoCount = factory.getMapper(MessageMapper.class).getToDoCount(user.getCode(), 0);
            // 获取是否有待审流程
            List<String> idList = new ArrayList<>();
            MessageEntity<?> totalMessage = null;
            try {
                totalMessage = workflowService.list(null, null, null, null, null, null, 2, null, user.getUserid(), 0, Integer.MAX_VALUE);
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }
            if (null != totalMessage) {
                List<LinkedHashMap> taskList = (List<LinkedHashMap>) totalMessage.getData();
                if (null != taskList && taskList.size() > 0) {
                    for (LinkedHashMap map : taskList) {
                        String billId = (String) map.get("billId");
                        idList.add(billId);
                    }
                }
            }
            Integer auditCount = 0;
            if (null != idList && idList.size() > 0) {
                auditCount = factory.getMapper(MessageMapper.class).getAuditCount(idList, 1);
            }
            Map map = new HashMap();
            map.put("unreadMessage", isReadCount > 0 ? true : false);
            map.put("unreadMessageCount", isReadCount);
            map.put("toDoTask", toDoCount > 0 ? true : false);
            map.put("toDoTaskCount", toDoCount);
            map.put("pendingProcess", auditCount > 0 ? true : false);
            map.put("pendingProcessCount", auditCount);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
            msg.setData(map);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
    }
}
